import uuid
from dataclasses import dataclass

from injector import inject

from internal.model import App
from pkg.sqlalchemy import SQLAlchemy


@inject
@dataclass
class AppService:
    """应用逻辑"""
    db: SQLAlchemy

    def update_app(self, aid: uuid.UUID):
        with self.db.auto_commit():
            app = self.get_app(aid)
            app.name = "逆天聊天机器人"
        return app

    def get_app(self, aid: uuid.UUID) -> App:
        app = self.db.session.query(App).get(aid)
        return app

    def create_app(self):
        try:
            with self.db.auto_commit():
                # 1.创建模型实体类
                app = App(name="聊天机器人", account_id=uuid.uuid4(), icon="", description="这是一个简单的聊天机器人")
                # 2.将实体类添加到session会话中
                self.db.session.add(app)
            return app
        except Exception as e:
            print("创建应用失败:", e)
            raise e

    def delete_app(self, aid: uuid.UUID):
        with self.db.auto_commit():
            app = self.get_app(aid)
            self.db.session.delete(app)
        return app
